package net.javacloud.service;

import org.jivesoftware.smack.*;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.MultiUserChatManager;

import java.io.IOException;
import java.util.Random;

/**
 * Created by Crowhyc on 2016/6/22.
 */
public class MsgSender implements Runnable {

    private String msg;
    private int interval;
    private final static String host = Tester.host;
    private final static int port = 5222;
    private XMPPTCPConnection connection;
    private int idx;
    private String roomId;
    private MultiUserChat muc;


    static {
        XMPPTCPConnection.setUseStreamManagementResumptionDefault(true);
        XMPPTCPConnection.setUseStreamManagementDefault(true);
        XMPPTCPConnection.setReplyToUnknownIqDefault(true);
        ReconnectionManager.setEnabledPerDefault(true);
    }


    private AbstractXMPPConnection initConnection(String username, String pwd) throws IOException, XMPPException, SmackException {
        if (connection != null) {
            if (!connection.isConnected()) {
                connection.connect().login();
                return connection;
            }
            return connection;
        }
        XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder().setCompressionEnabled(true).setUsernameAndPassword(username, pwd).setServiceName(host).setHost(host).setPort(port).setSecurityMode(XMPPTCPConnectionConfiguration.SecurityMode.disabled).setDebuggerEnabled(false).build();
        /** 创建connection链接 */
        /** 建立连接  */

        connection = new XMPPTCPConnection(config);
        connection.connect().login();
        ChatManager chatManager = ChatManager.getInstanceFor(connection);
        chatManager.addChatListener((chat, createdLocally) -> chat.addMessageListener((ChatMessageListener) (chat1, message) -> System.out.println(message.getFrom() + " say: " + message.getBody())));
        idx = Tester.connectionMap.size();
        Tester.connectionMap.put(username, this);
        MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
        muc = manager.getMultiUserChat(roomId + "@conference." + AccountRegister.getConnection().getServiceName());
        muc.addMessageListener(message -> System.out.println("接受到消息:" + message.getBody()));
        muc.join("测试者" + idx);
        return connection;
    }


    private void sendMsg(String text) throws SmackException, IOException, XMPPException {
        if (!connection.isConnected()) {
            connection.connect().login();
        }
        Message msg = new Message();
        msg.setBody(connection.getConfiguration().getUsername() + " 说: " + text);
        msg.setType(Message.Type.normal);
        muc.sendMessage(msg);
    }

    public MsgSender(String username, String password, String msg, int interval, String roomId) throws XMPPException, IOException, SmackException {
        this.msg = msg;
        this.interval = interval;
        this.roomId = roomId;
        initConnection(username, password);
    }

    @Override
    public void run() {
        try {
            int i = 0;
            while (Tester.flag) {
                sendMsg(msg + "  第" + i++ + "次");
                Thread.sleep(interval * 1000);
            }
            muc.leave();
            AccountRegister.delUser(connection);
        } catch (IOException | XMPPException | InterruptedException | SmackException e) {
            e.printStackTrace();
        }
    }


}
